<?php


namespace app\model\member;

use app\model\BaseModel;
use app\model\pay\Huifu;
use app\model\system\Pay;

class MrnaApply extends BaseModel
{


    public $pay_type = [
        //'ONLINE_PAY' => '在线支付',
        'BALANCE' => '余额支付',
        'OFFLINE_PAY' => '线下支付'
    ];

    /**
     * 获取支付方式
     */
    public function getPayType()
    {
        //获取订单基础的其他支付方式
        $pay_type = $this->pay_type;
        //获取当前所有在线支付方式
        $onlinepay = event('PayType', []);
        if (!empty($onlinepay)) {
            foreach ($onlinepay as $k => $v) {
                $pay_type[ $v[ 'pay_type' ] ] = $v[ 'pay_type_name' ];
            }
        }
        return $pay_type;
    }

    public function apply($apply_data)
    {
        model('mrna_apply')->startTrans();
        try {
            $member_id = isset($apply_data[ 'member_id' ]) ? $apply_data[ 'member_id' ] : 0;

            //添加申请信息
            $apply_data[ 'create_time' ] = time();

            $apply_data[ 'apply_no' ] = date('YmdHi') . rand(1111, 9999);

            //获取商家申请信息
            $apply_info = model('mrna_apply')->getInfo([ [ 'member_id', '=', $member_id ] ]);

            if ($apply_info) {
                //判断认证信息是否存在
                $res = model('mrna_apply')->update($apply_data, [ [ 'member_id', '=', $member_id ] ]);

            } else {

                $res = model('mrna_apply')->add($apply_data);
            }

            model('mrna_apply')->commit();
            return $this->success($res);
        } catch (\Exception $e) {
            model('mrna_apply')->rollback();
            return $this->error('', $e->getMessage());
        }

    }

    /**
     * 添加
     *
     * @param array $data
     */
    public function addMrnaApply($data)
    {

        $res = model('mrna_apply')->add($data);

        return $this->success($res);
    }

    /**
     * 修改
     *
     * @param array $data
     * @param array $condition
     */
    public function editMrnaApply($data, $condition)
    {

        $res = model('mrna_apply')->update($data, $condition);

        return $this->success($res);
    }

    /**
     * 删除
     * @param array $condition
     */
    public function deleteMrnaApply($condition)
    {
        $res = model('mrna_apply')->delete($condition);

        return $this->success($res);
    }

    public function getMrnaApplyInfo($condition = [], $field = '*')
    {
        $info = model('mrna_apply')->getInfo($condition, $field);

        return $this->success($info);
    }

    public function getMrnaApplyList($condition = [], $field = '*', $order = 'create_time desc', $limit = null)
    {
        $list = model('mrna_apply')->getList($condition, $field, $order, '', '', '', $limit);

        return $this->success($list);
    }


    public function getMrnaApplyPageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = 'create_time desc', $field = '*',$alias='a',$join=[])
    {
        $list = model('mrna_apply')->pageList($condition, $field, $order, $page, $page_size,$alias,$join);

        return $this->success($list);
    }


    //审核
    public function audit($apply_id,$apply_state,$reason)
    {
        $res = model('mrna_apply')->update(['apply_state'=>$apply_state,'reason'=>$reason],[['apply_id','=',$apply_id]]);
        return $this->success($res);
    }


    //签署合同
    public function confrinSign($apply_id,$contract_no,$level,$price)
    {
        model("mrna_apply")->startTrans();

        try {

            $condition = [
                ['apply_id','=',$apply_id]
            ];

            $info = model('mrna_apply')->getInfo($condition);

            $pay = new Pay();

            $out_trade_no = $pay->createOutTradeNo($info['member_id']);

            $data = [
                'contract_no'  =>  $contract_no,
                'level'    =>  $level,
                'price'    =>  $price,
                'out_trade_no'   =>  $out_trade_no,
                'apply_state'   =>  3
            ];

            $pay_type = 'ONLINE_PAY';

            $order_name_title = '加盟商费用';

            $pay->addPay(0, $out_trade_no, $pay_type,$order_name_title , $order_name_title, $price, '', 'MrnaSignPayNotify', '');

            $res = model('mrna_apply')->update($data,$condition);

            model("mrna_apply")->commit();

            return $this->success($res);

        } catch ( \Exception $e ) {
            model("mrna_apply")->rollback();
            return $this->error('', $e->getMessage() . $e->getFile() . $e->getLine());
        }


    }


    //解除加盟商
    public function removeMrna($apply_id)
    {
        $condition = [
            ['apply_id','=',$apply_id]
        ];

        $order_info = model('mrna_apply')->getInfo($condition);

        $data = [
            'status'=>-1,
            'remove_time'=>time()
        ];

        model('member')->update(['is_mrna'=>0],[['member_id','=',$order_info['member_id']]]);

        $res = model('mrna_apply')->update($data,$condition);

        return $this->success($res);
    }

    //用户申请退出
    public function quitMrna($apply_id,$member_id)
    {

        $condition = [
            ['apply_id','=',$apply_id],
            ['member_id','=',$member_id]
        ];
        
        $info = model('mrna_apply')->getInfo($condition);

        if (empty($info)){
            return $this->error('','申请记录不存在');
        }
        if ($info[ 'pay_status' ] == 0) {
            return $this->error('','暂未成为加盟商');
        }
        if ($info[ 'quit_status' ] == 1) {
            return $this->error('','已申请退出待平台审核');
        }
        if ($info[ 'status' ] == -1) {
            return $this->error('','平台已解除');
        }

        $data = [
            'quit_status'=>1,
            'member_apply'=>1
        ];

        $res = model('mrna_apply')->update($data,$condition);

        return $this->success($res);

    }

    //审核
    public function quitAudit($apply_id,$quit_status,$quitreason)
    {
        $condition = [
            ['apply_id','=',$apply_id],
        ];

        $info = model('mrna_apply')->getInfo($condition);

        if (empty($info)){
            return $this->error('','申请记录不存在');
        }

        if ($info[ 'quit_status' ] != 1) {
            return $this->error('','已审核');
        }

        if ($info[ 'status' ] == -1) {
            return $this->error('','平台已解除');
        }

        $data = [
            'quit_status'=>$quit_status,
            'quitreason'=>$quitreason,
            'status'=>-1
        ];

        $res = model('mrna_apply')->update($data,$condition);

        return $this->success($res);
    }

    public function submitHuifu($apply_id)
    {
        model('mrna_apply')->startTrans();

        try {
            $mrna_info = model('mrna_apply')->getInfo(['apply_id'=>$apply_id]);

            $huifu_model = new Huifu();

            $data = [
                'name'=>$mrna_info['id_card_name'],
                'id_card_num'=>$mrna_info['id_card_number'],
                'id_card_start_time'=>$mrna_info['id_card_start_time'],
                'id_card_end_time'=>$mrna_info['id_card_end_time'],
                'mobile'=>$mrna_info['mobile'],
                'id_card_time_type'=>$mrna_info['id_card_time_type'],
            ];

            $res = $huifu_model->personalAccountOpening($data);

            if ($res[ "code" ] < 0)
                return $res;

            $data = [
                'huifu_id'=>$res['data']['huifu_id'],
                'login_name'=>$res['data']['login_name'] ?? '',
                'login_password'=>$res['data']['login_password'] ?? '',
            ];

            $res = model('mrna_apply')->update($data,[['apply_id','=',$apply_id]]);

            model('mrna_apply')->commit();

            return $this->success($res);
        } catch (\Exception $e) {
            model('mrna_apply')->rollback();
            return $this->error('', $e->getMessage());
        }


    }

    /**
     * 订单线下支付
     * @param $order_id
     * @return array
     */
    public function orderOfflinePay($out_trade_no)
    {
        model('mrna_apply')->startTrans();
        try {

            $pay_model = new Pay();
            $result = $pay_model->onlinePay($out_trade_no, "OFFLINE_PAY", '', '');
            if ($result[ "code" ] < 0) {
                model('mrna_apply')->rollback();
                return $result;
            }
            model('mrna_apply')->commit();
            return $result;
        } catch (Exception $e) {
            model('mrna_apply')->rollback();
            return $this->error('', $e->getMessage());
        }
    }


    //支付回调
    public function onlinePay($data)
    {
        model('mrna_apply')->startTrans();

        try {
            $out_trade_no = $data[ "out_trade_no" ];
            $pay_type = $data[ 'pay_type' ] ?? 'ONLINE_PAY';

            $pay_type_list = $this->getPayType();

            $order_info = model('mrna_apply')->getInfo(['out_trade_no'=>$out_trade_no]);

            if ($order_info[ 'pay_status' ] != 0) {
                return $this->error();
            }
            $condition = array (
                [ "apply_id", "=", $order_info[ "apply_id" ] ],
            );
            $data = array (
                "pay_status" => 1,
                "pay_time" => time(),
                "pay_type" => $pay_type,
                "pay_type_name" => $pay_type_list[ $pay_type ],
                "apply_state"=>4,
                "status" => 1
            );

            model('member')->update(['is_mrna'=>1],[['member_id','=',$order_info['member_id']]]);

            $result = model("mrna_apply")->update($data, $condition);

            model('mrna_apply')->commit();

            return $this->success($result);

        } catch (Exception $e) {
            model('mrna_apply')->rollback();
            return $this->error('', $e->getMessage());
        }
    }
}